﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Text;

public partial class msg : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        this.Theme = Session["theme"].ToString();
        this.Title = "MaxBlox";
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        setPageTitle();
        if (!IsPostBack)
        {
            string msg_id = "", sContinueURl = "";
            bool show_msg = false;
            if (Request.QueryString["id"] != null)
                msg_id = Request.QueryString["id"].ToString();
            if (Request.QueryString["url"] != null)
                sContinueURl = HttpUtility.UrlDecode(Request.QueryString["url"].ToString());
            if (HttpContext.Current.Session["user_afrowid"] != null && HttpContext.Current.Session["user_afrowid"].ToString().Trim() != "")
                show_msg = getAccessToShowMsg(msg_id, HttpContext.Current.Session["user_afrowid"].ToString());
            if (!show_msg)
                Response.Redirect(sContinueURl);
        }
    }
    private bool getAccessToShowMsg(string msg_id, string sCurrent_User_id)
    {
        HDDatabase hdd = new HDDatabase();
        DataTable dtMsg = new DataTable();
        DataTable dtMembers = new DataTable();
        DataTable dtMemberLogs = new DataTable();
        try
        {
            dtMsg = hdd.GetDataTable("select * from sy_messages where af_row_id = '" + msg_id + "';");
            if (dtMsg.Rows.Count == 0) return false;

            // handle audience type
            switch (dtMsg.Rows[0]["audience_type"].ToString().ToLower())
            {
                case "rb":
                    dtMembers = hdd.GetDataTable("select * from sy_usr where af_row_id in (select user_id from sy_usr_rol where role_id in (select af_row_id from sy_rol where role_name in (select audience_members_id from sy_message_audience_members where audience_type in ('" + dtMsg.Rows[0]["af_row_id"].ToString() + "'))));");
                    break;
                case "ub":
                    dtMembers = hdd.GetDataTable("select * from sy_usr where user_id in (select audience_members_id from sy_message_audience_members where audience_type in ('" + dtMsg.Rows[0]["af_row_id"].ToString() + "'));");
                    break;
            }
            if (dtMembers.Rows.Count > 0)
            {
                DataRow[] dr = dtMembers.Select("af_row_id = '" + sCurrent_User_id + "'");
                if (dr.Length == 0)
                    return false;
            }
            else if (dtMsg.Rows[0]["audience_type"].ToString().ToLower() != "all")
                return false;

            // handle message type
            dtMemberLogs = hdd.GetDataTable("select * from sy_message_audience_logs where message_id = '" + dtMsg.Rows[0]["af_row_id"].ToString() + "' order by modified_at desc;");
            switch (dtMsg.Rows[0]["type"].ToString().ToLower())
            {
                case "cb": // Count based
                    if (dtMsg.Rows[0]["counts_days"].ToString() == "") return false;
                    if (dtMemberLogs.Rows.Count > 0)
                    {
                        DataRow[] dr = dtMemberLogs.Select("user_id = '" + sCurrent_User_id + "'");
                        if (dr.Length > Convert.ToInt32(dtMsg.Rows[0]["counts_days"].ToString()))
                            return false;
                    }
                    break;
                case "db": // Day based
                    if (dtMsg.Rows[0]["counts_days"].ToString() == "") return false;
                    DateTime CreatedAt = Convert.ToDateTime(dtMsg.Rows[0]["created_at"].ToString());
                    DateTime CurrentDate = DateTime.Now;
                    TimeSpan difference = CurrentDate.Subtract(CreatedAt);
                    int TotalDays = Convert.ToInt32(difference.TotalDays);
                    if (TotalDays > Convert.ToInt32(dtMsg.Rows[0]["counts_days"].ToString()))
                        return false;
                    break;
                case "bd": // Between dates
                    if (dtMsg.Rows[0]["start_date"].ToString() == "" || dtMsg.Rows[0]["end_at"].ToString() == "") return false;
                    DateTime StartDate = Convert.ToDateTime(dtMsg.Rows[0]["start_date"].ToString());
                    DateTime EndDate = Convert.ToDateTime(dtMsg.Rows[0]["end_at"].ToString());
                    DateTime TodayDate = DateTime.Now;
                    if (StartDate > EndDate) return false;
                    if (StartDate <= TodayDate && TodayDate >= EndDate)
                        return false;
                    break;
                case "ua": // Until Agreed
                    if (dtMemberLogs.Rows.Count > 0)
                    {
                        DataRow[] dr = dtMemberLogs.Select("user_id = '" + sCurrent_User_id + "'");
                        if (dr.Length > 0 && Convert.ToBoolean(dr[0]["agreed"].ToString()))
                            return false;
                    }
                    ch_agreed.Visible = true;
                    break;
            }
            lbl_message.Text = dtMsg.Rows[0]["message"].ToString();
        }
        catch (Exception ee)
        {
            LogWriter.WriteLog("Error " + ee.Message + " in getAccessToShowMsg Function");
        }
        finally
        {
            hdd = null;
        }
        return true;
    }

    protected void bt_continue_Click(object sender, EventArgs e)
    {
        SqlCommand sqlCmd = null;
        HDDatabase hdd = new HDDatabase();
        ScreenReader SR = new ScreenReader();
        string msg_id = "", sContinueURl = "", sCurrent_User_id = "";
        bool isAgreed = false;
        try
        {
            if (Request.QueryString["id"] != null)
                msg_id = Request.QueryString["id"].ToString();
            if (Request.QueryString["url"] != null)
                sContinueURl = HttpUtility.UrlDecode(Request.QueryString["url"].ToString());
            sCurrent_User_id = HttpContext.Current.Session["user_afrowid"].ToString();
            isAgreed = ch_agreed.Checked;
            // add message logs
            string sInsert = "INSERT INTO [sy_message_audience_logs]([message_id],[user_id],[agreed],[af_row_id],[created_by],[created_at],[modified_at],[modified_by],[owner_id])"
                + "VALUES('" + msg_id + "','" + sCurrent_User_id + "'," + (isAgreed ? 1 : 0) + ",'" + SR.getHashKey() + "','e51e0327224a2eb9','" + DateTime.Now.ToString() + "','" + DateTime.Now.ToString() + "','e51e0327224a2eb9','e51e0327224a2eb9')";
            sqlCmd = new SqlCommand(sInsert);
            int execute = hdd.ExecuteCmdObj(sqlCmd);
            Response.Redirect(sContinueURl, false);
        }
        catch (Exception ee)
        {
            LogWriter.WriteLog("Error " + ee.Message + " in bt_continue_Click Function");
        }
        finally
        {
            hdd = null; sqlCmd = null; SR = null;
        }
    }
    private void setPageTitle()
    {
        try
        {
            if (Session["pageTitle"] != null)
            {
                Page.Header.Title = Session["pageTitle"].ToString();
            }
            else
            {
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini"))
                {
                    System.IO.StreamReader sr = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(".") + "\\maxbloxtitle.ini");
                    Session["pageTitle"] = sr.ReadLine();
                    Page.Header.Title = Session["pageTitle"].ToString();
                    sr.Close();
                    sr = null;
                }
            }
        }
        catch (Exception e)
        {
            LogWriter.WriteLog("Error in setPageTitle function. Error: " + e.Message);
        }
    }
}